package com.example.reagent_management.di

import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton

/**
 *
 * @Inject
    @ApplicationScope
    lateinit var appScope:CoroutineScope
 *
 */

@InstallIn(SingletonComponent::class)
@Module
object CoroutinesScopesModule {

    /**
     * 由于在 Android 中没有可靠的方法来获取 Application 销毁的时机，
     * 并且应用级别的作用域以及任何正在执行的任务都将同应用进程的结束一同销毁，
     * 也意味着您无需手动调用 applicationScope.cancel()。
     */
    @Singleton  // 永远提供相同实例
    @Provides
    @ApplicationScope
    fun providesCoroutineScope(@DefaultDispatcher defaultDispatcher: CoroutineDispatcher): CoroutineScope {
        // 当提供 CoroutineScope 实例时，执行如下代码
        return CoroutineScope(SupervisorJob() + defaultDispatcher)
    }

    @DefaultDispatcher
    @Provides
    fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default

    @IoDispatcher
    @Provides
    fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO

    @MainDispatcher
    @Provides
    fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main

    @MainImmediateDispatcher
    @Provides
    fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
}